package com.solr.product.dao.impl;

import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;

import com.solr.product.bean.Product;
import com.solr.product.dao.BaseDao;
import com.solr.product.dao.ProductDao;


public class ProductDaoImpl extends BaseDao implements ProductDao{

	public void add(Product product) {
		String sql = "insert into t_product (id, name, storeid,createdate) values (?,?,?,?)";
		List<Object> params = new ArrayList<Object>();
		params.add(product.getId());
		params.add(product.getName());
		params.add(product.getStoreid());
		params.add(new Date(System.currentTimeMillis()));
		getIndexDBTemplate().update(sql, params.toArray());
	}

	public void update(Product product) {
		// TODO Auto-generated method stub
		
	}

	public Product getProduct(int id) {
		String sql = "select * from t_product where id = ?";
		Object[] params = {id};
		Product product = getIndexDBTemplate().query(sql, params, new ResultSetExtractor<Product>(){

			public Product extractData(ResultSet rs) throws SQLException,
					DataAccessException {
				return getResult(rs);
			}
			
		});
		return product;
	}

	public List<Product> getProductPage(int start, int limit) {
		String sql = "select * from t_product where id >=(select id from t_product limit ?,1 ) limit ?";
		List<Object> params = new ArrayList<Object>();
		params.add(start);
		params.add(limit);
		List<Product> list = getIndexDBTemplate().query(sql, params.toArray(), new RowMapper<Product>(){

			public Product mapRow(ResultSet rs, int row) throws SQLException {
				return getResult(rs);
			}

			
			
		});
		return list;
	}
	
	private Product getResult(ResultSet rs) throws SQLException {
		Product product = new Product();
		product.setId(rs.getInt("id"));
		product.setName(rs.getString("name"));
		product.setStoreid(rs.getInt("storeid"));
		product.setCreateDate(rs.getDate("createdate"));
		return product;
	}

}
